/**
 * This library is used to modify the cpf desktop with different styles.
 * Requisites for the library to work
 *   1. The facing tab(tab that the user first sees when he logs in) presented to the user should not be any
 *      of the CPF standard tabs - My Page, Setup, Reports
 *   2. The facing tab should not be a multi form tab
 *   3. The facing tab should be a single form tab. The library should be attached to this form on its form init event
 *   4. custom_desktop.css has to be attached from the script library to the breadcrum frame
 *   5. Only works browsers with HTML5 support
 * The library should be attached to every form that comes as the facing form for different privileges
 */

(function() {
	if(!window["vg"]) {
		vg = {};
	}
	
	//if cpfdesktop exists, then it means that the desktop has already been modified by a previous form
	if(!vg.cpfdesktop) {
		vg.cpfdesktop = {};
	}
	
	var identifiers = {
		"desktopFrame": "desktop",
		"breadcrumFrame": "breadcrum",
		"headerDiv": "header",
		"appLogo": "applicationLogo",
		"appTitle": "applicationTitle",
		"changeApp": "Click here to change Application",
		"userName": "loginName",
		"profile": "View Profile",
		"logOut": "Log Out",
		"myProfileDiv": "myProfileDiv"
		
	}
	var classObj = {
		"header" : {
			"containerDiv": "custom-header",
			"bold": "bold-weight"
		}
	}
	
	if(!top.customHeaderConfig) {
		top.customHeaderConfig = {}
	}
	var configObj = top.customHeaderConfig;
	
	var headerOptions, headerData;
	/***************************************** Internally used functions *************************************/
	function init() {
		//checking if the header has been already created by some other form
		if(configObj["headerOptions"]) {
			headerOptions = configObj["headerOptions"];
			headerData = configObj["headerData"];
			return;
		}
		configObj["headerOptions"] = headerOptions = {};
		configObj["headerData"] = headerData = {};
		configObj["desktopDoc"] = top.document.getElementById(identifiers["desktopFrame"]).contentWindow.document;
		configObj["myProfileDiv"] = configObj["desktopDoc"].getElementById(identifiers["myProfileDiv"]);
		configObj["breadDoc"] = configObj["desktopDoc"].getElementById(identifiers["breadcrumFrame"]).contentWindow.document;
		configObj["appHeaderDiv"] = configObj["breadDoc"].getElementById(identifiers["headerDiv"]);
		//creating the custom header
		configObj["customHeaderDiv"] = document.createElement("div");
		configObj["customHeaderDiv"].className = classObj["header"]["containerDiv"];
		configObj["appHeaderDiv"].appendChild(configObj["customHeaderDiv"]);
		//set the custom header with default library provided styles
		setHeader();
	}
	
	//Extracting required details from the actual application header
	function setHeader() {
		//Setting the logo image
		var appHeaderDiv = configObj["appHeaderDiv"];
		var customHeaderDiv = configObj["customHeaderDiv"];
		headerData.appLogoElmt = configObj["appHeaderDiv"].querySelector("#" + identifiers["appLogo"]).cloneNode();
		headerData.appLogoElmt.id = "customAppLogo";
		var container = document.createElement("div");
		container.setAttribute("customType", "titleContainer");
		var imgContainer = document.createElement("div");
		imgContainer.appendChild(headerData.appLogoElmt);
		container.appendChild(imgContainer);
		
		//Setting the title
		headerData.appTitle = appHeaderDiv.querySelector("#" + identifiers["appTitle"]).innerHTML;
		headerData.appTitleElmt = document.createElement("div");
		headerData.appTitleElmt.setAttribute("customType", "title");
		headerData.appTitleElmt.innerHTML = headerData.appTitle;
		container.appendChild(headerData.appTitleElmt);
		customHeaderDiv.appendChild(container);
		
		//setting links
		var linksHtml = '<a href="javascript:void(0)" id="customProfile"><div>{UserName}</div><div style="margin-top:3px;">{UserID}</div></a><div><a href="javascript:void(0)" class="' + classObj["header"]["bold"] + '" id="customChangeApplication"><div>Change Application</div></a><a href="javascript:void(0)" class="' + classObj["header"]["bold"] + '" id="customLogOut"><div style="margin-top:3px;">Log out</div></a></div>';
		container = document.createElement("div");
		container.setAttribute("customType", "userLinkContainer");
		headerData.userName = appHeaderDiv.querySelector("#" + identifiers["userName"]).innerHTML.replace(/Welcome\s(.*?)!/, "$1");
		headerData.userId = GlobalVariables.currentuser;
	    linksHtml = linksHtml.replace("{UserID}", headerData.userId);
	    linksHtml = linksHtml.replace("{UserName}", headerData.userName);	
		container.innerHTML = linksHtml;	
		headerData.changeAppElmt = appHeaderDiv.querySelector("[title = '" + identifiers["changeApp"] + "']");
		headerData.profileElmt = appHeaderDiv.querySelector("[title = '" + identifiers["profile"] + "']");
		headerData.logOutElmt = appHeaderDiv.querySelector("[title = '" + identifiers["logOut"] + "']");
	    customHeaderDiv.appendChild(container);
		
		//setting events
		customHeaderDiv.querySelector("#customLogOut").onclick = function(){
			headerData.logOutElmt.dispatchEvent(getClickEvt(configObj["breadDoc"]));
		}
	    customHeaderDiv.querySelector("#customChangeApplication").onclick = function(){
			headerData.changeAppElmt.dispatchEvent(getClickEvt(configObj["breadDoc"]));
		}
	    customHeaderDiv.querySelector("#customProfile").onclick = function () {
			headerData.profileElmt.dispatchEvent(getClickEvt(configObj["breadDoc"]));
	        var popupWidth = configObj["myProfileDiv"].offsetWidth;
			var userNamePos = this.offsetLeft;
	        configObj["myProfileDiv"].style.left = (userNamePos - popupWidth)+ "px"
	    }		
	}
	
	//To get a click event for the document object passed
	function getClickEvt(doc) {
		var clickEvt = doc["createEvent"]("MouseEvents");
		clickEvt.initMouseEvent("click", true, true, undefined, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
		return clickEvt;	
	}
	
	function headerRefresh() {
		headerData.appLogoElmt.parentNode.display = headerOptions.showAppImage ? "block" : "none";
		if(headerOptions.colors) {
			headerOptions.colors.background && (configObj["customHeaderDiv"].style.background = headerOptions.colors.background);
		}
	}
	
	/***************************************** Exposed utility functions *************************************/
	//To set header options
	vg.cpfdesktop.setHeaderOptions = function (options) {
		headerOptions.showAppImage = options.showAppImage || true;
		headerOptions.colors = options.colors || undefined;
	}
	
	//To set visibility of the header
	vg.cpfdesktop.showHeader = function(isVisible) {
		configObj["customHeaderDiv"].style.display = isVisible ? "block" : "none";
	}
	
	//To refresh the header with the new settings after header options have been changed
	vg.cpfdesktop.refresh = function () {
		headerRefresh();
	}
	
	/****************************************** And so it begins *******************************************/
	init();
	scriptCallback && scriptCallback("CPF Desktop");
})();
